import * as React from "react";
import { observer } from "mobx-react";
import { observable } from "mobx";
import {
  Row,
  Col,
  Button,
  Table,
  Modal,
  Form,
  Input,
  Select,
  Typography,
  Space,
  TreeSelect,
  Spin,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { AjaxData } from "../../../../../../data/interface/publicInterface";
import IconFont from "../../../../../../assets/ICON";

import {
  listToAntdTreeSelectTreeData,
  getUserInfo,
} from "../../../../../../utils/common";
import {
  getUserFind,
  getfindAllDepartment,
  getfindAllRole,
  addUser,
  deleteUser,
  updateUser,
} from "../../../ServeApi";
import md5 from "js-md5";
import { WebVariable } from "../../../../../../data/WebVariable";
import "./index.less";
const { Option } = Select;
const { Text } = Typography;
const salt = WebVariable.salt;

export interface UserTableProps {
  dataSouce: any;
}

export interface UserTableState {}

interface columnsDataCLass {
  title: string;
  dataIndex: string;
  key: string;
  render?: any;
}

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
    md: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
    md: { span: 16 },
  },
};
@observer
class UserTable extends React.Component<UserTableProps, UserTableState> {
  @observable private columns: columnsDataCLass[] = [
    {
      title: "用户姓名",
      dataIndex: "realName",
      key: "realName",
    },
    {
      title: "账号",
      dataIndex: "loginName",
      key: "loginName",
    },
    {
      title: "角色",
      dataIndex: "roleName",
      key: "roleName",
    },
    {
      title: "用户类型",
      dataIndex: "isDefault",
      key: "isDefault",
      render: (text, record) => {
        return <>{text === "1" ? "默认用户" : "非默认用户"}</>;
      },
    },
    {
      title: "部门",
      dataIndex: "orgName",
      key: "orgName",
    },
    {
      title: "操作",
      dataIndex: "ii",
      key: "roleName",
      render: (text, record) => {
        return (
          <>
            <Space size={26}>
              <span
                style={{ color: "#595959", cursor: "pointer" }}
                onClick={() => {
                  this.Mod = "updata";
                  this.onEdit(record);
                }}
              >
                <IconFont
                  type="icon_form_bianji"
                  style={{ color: "#FBB10B" }}
                />
                <Text>编辑</Text>
              </span>
              {record.isDefault === "1" ||
              getUserInfo("loginName") === record.name ? null : (
                <span
                  style={{ color: "#595959", cursor: "pointer" }}
                  onClick={() => {
                    this.onDelete(record);
                  }}
                >
                  <IconFont
                    type="icon_form_shanchu"
                    style={{ color: "#FF6B6B" }}
                  />
                  <Text>删除</Text>
                </span>
              )}
            </Space>
          </>
        );
      },
    },
  ];
  @observable private isModalVisible: boolean = false;
  @observable private isModalMenuwarrant: boolean = false;
  private instance: any = null;
  private dataSouce: any[] = [];
  private pageIndex: number = 1;
  private pageSize: number = 20;
  private total: number = 0;
  private TreeSelectTreeData: any = null; //部门树tree
  private RoleData: any[] = []; //角色数据
  private departmentList: any[] = [];
  private Mod: string = "add";
  private initValue: any = null;
  state = {
    loading: false,
  };
  render() {
    return (
      <>
        <div className="rowcon_body">
          <div>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                this.Mod = "add";
                this.addMenuModal();
              }}
            >
              新增
            </Button>
          </div>
          <div className="rowcon_bottom"></div>
          <Spin spinning={this.state.loading}>
            <Table
              columns={this.columns}
              dataSource={this.dataSouce}
              pagination={{
                pageSize: this.pageSize,
                total: this.total,
                current: this.pageIndex,
                onChange: (page: number) => {
                  this.pageIndex = page;
                  this.getPream();
                },
              }}
            ></Table>
          </Spin>
          <Modal
            title={this.Mod === "add" ? "新增用户" : "编辑用户"}
            visible={this.isModalVisible}
            onOk={() => {
              this.handleOk();
            }}
            onCancel={() => {
              this.handleCancel();
            }}
          >
            <Form {...formItemLayout} ref={(el) => (this.instance = el)}>
              <Row>
                <Col span={24}>
                  <Form.Item
                    label="账号："
                    name="loginName"
                    rules={[
                      {
                        required: true,
                        message: "请填写账号",
                      },
                    ]}
                  >
                    <Input placeholder="请填写账号" />
                  </Form.Item>
                </Col>
                {this.Mod === "add" ? (
                  <Col span={24}>
                    <Form.Item label="密码：" name="password">
                      <Input placeholder="不填写则为默认密码" />
                    </Form.Item>
                  </Col>
                ) : null}

                <Col span={24}>
                  <Form.Item
                    label="用户姓名："
                    name="realName"
                    rules={[
                      {
                        required: true,
                        message: "请填写用户姓名",
                      },
                    ]}
                  >
                    <Input placeholder="请填写用户姓名" />
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item
                    label="角色："
                    name="roleId"
                    rules={[
                      {
                        required: true,
                        message: "请选择角色",
                      },
                    ]}
                  >
                    <Select placeholder="请选择用户角色">
                      {this.RoleData.map((item: any) => {
                        return (
                          <Option value={item.id} key={item.id}>
                            {item.name}
                          </Option>
                        );
                      })}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item
                    label="所属部门："
                    name="treeId"
                    rules={[
                      {
                        required: true,
                        message: "请选择部门",
                      },
                    ]}
                  >
                    <TreeSelect
                      treeData={this.TreeSelectTreeData}
                      // onChange={(value: any) => {
                      //   this.onChange(value);
                      // }}
                    ></TreeSelect>
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Modal>
        </div>
      </>
    );
  }
  /**钩子函数 */
  componentWillMount() {
    this.init();
  }
  /**请求函数 */
  //获取角色数据
  async getRoleData() {
    let _this = this;
    this.setState({ loading: true });
    let res = await getfindAllRole().catch((err) => {
      console.log(err);
      _this.setState({ loading: false });
    });
    if (res) {
      let Json: any = res;
      if (Json.success) {
        this.RoleData = Json.data;
        this.setState({ loading: false });
        this.forceUpdate();
      } else {
        Modal.error({
          title: Json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    }
  }
  //请求部门数据
  async getDepartmentData() {
    let _this = this;
    _this.setState({ loading: true });
    let prom: any = await getfindAllDepartment().catch((err) => {
      if (err) {
        console.log(err);
      }
    });
    if (prom) {
      let res: AjaxData = prom;
      if (res.success) {
        this.departmentList = res.data;
        this.TreeSelectTreeData = listToAntdTreeSelectTreeData(res.data);
        _this.setState({ loading: false });
        this.forceUpdate();
      } else {
        Modal.warning({
          title: res.message,
          onOk() {
            _this.setState({ loading: false });
          },
        });
      }
    }
  }
  //获取初始用户列表
  getUserListData() {
    let pream = {
      pageIndex: this.pageIndex,
      pageSize: this.pageSize,
      likeStr: "",
    };
    let _this = this;
    this.setState({ loading: true });
    getUserFind(JSON.stringify(pream))
      .then((rnt: any) => {
        if (rnt) {
          let res: AjaxData = rnt;
          if (res.success) {
            this.setState({ loading: false });
            // this.init();
            this.dataSouce = res.data.records;
            this.total = res.data.total;
            this.forceUpdate();
          } else {
            Modal.error({
              title: res.message,
              onOk: () => {
                _this.setState({ loading: false });
              },
            });
          }
        }
      })
      .catch((err) => {
        this.setState({ loading: false });
      });
  }
  //删除用户
  DeleteUserItem(pream: iDeleUser) {
    let _this = this;
    this.setState({ loading: true });
    deleteUser(JSON.stringify(pream))
      .then((rnt: any) => {
        let res: AjaxData = rnt;
        if (res.success) {
          this.init();
        } else {
          Modal.error({
            title: res.message,
            onOk: () => {
              _this.setState({ loading: false });
            },
          });
        }
      })
      .catch((err) => {});
  }
  //参数处理与新增，编辑函数
  setPream(item: IUserFromDataClass) {
    let _this = this;
    for (let key in item) {
      item[key] = item[key] ? item[key] : null;
    }
    let zc: any = this.getDepartmentid(item.treeId);
    item.orgId = zc.id;
    delete item.treeId;
    switch (this.Mod) {
      case "add":
        if (item.password) {
          item.password = md5(item.password + salt);
        } else {
          item.password = md5("Wy123456" + salt);
        }
        addUser(JSON.stringify(item))
          .then((rnt: any) => {
            let res: AjaxData = rnt;
            if (res.success) {
              this.init();
            } else {
              Modal.error({
                title: res.message,
                onOk: () => {
                  _this.setState({ loading: false });
                },
              });
            }
          })
          .catch((err) => {});
        break;
      case "updata":
        item.id = this.initValue.id;
        updateUser(JSON.stringify(item))
          .then((rnt: any) => {
            let res: AjaxData = rnt;
            if (res.success) {
              this.init();
            } else {
              Modal.error({
                title: res.message,
                onOk: () => {
                  _this.setState({ loading: false });
                },
              });
            }
          })
          .catch((err) => {});
        break;
      default:
        break;
    }
  }
  /**操作方法 */
  init() {
    this.getUserListData();
    this.getDepartmentData();
    this.getRoleData();
  }
  //翻页方法
  getPream() {
    this.getUserListData();
  }
  //编辑用户
  onEdit(item) {
    this.initValue = item;
    this.ifVisible();
    setTimeout(() => {
      if (this.instance) {
        const container: any = (this.instance as any) as HTMLDivElement;
        container.setFieldsValue(item);
      }
    });

    // console.log(item);
  }

  //新增菜单对话框
  addMenuModal() {
    this.ifVisible();
  }
  ifVisible() {
    this.isModalVisible = !this.isModalVisible;
    this.forceUpdate();
  }
  //删除用户
  onDelete(item) {
    let pream = {
      userId: item.id,
    };
    let _this = this;
    Modal.confirm({
      title: "是否确认删除用户",
      onOk: () => {
        _this.DeleteUserItem(pream);
      },
    });
  }
  //根据treeid获取id
  getDepartmentid(treeId) {
    let oIO = null;
    this.departmentList.map((item) => {
      if (treeId === item.treeId) {
        oIO = item;
      }
      return item;
    });
    return oIO;
  }
  handleOk() {
    // this.ifVisible();
    let _this = this;

    const container: any = (this.instance as any) as HTMLDivElement;
    container
      .validateFields()
      .then((res) => {
        _this.setPream(res);
        _this.ifVisible();
        _this.clearFromData();
      })
      .catch((err) => {
        console.log(err);
      });
  }
  handleCancel() {
    this.ifVisible();
    this.clearFromData();
  }

  //清空From表单
  clearFromData() {
    this.initValue = null;
    if (this.instance) {
      const container: any = (this.instance as any) as HTMLDivElement;
      container.setFieldsValue({
        loginName: undefined,
        orgId: undefined,
        treeId: undefined,
        orgName: undefined,
        password: undefined,
        roleId: undefined,
        realName: undefined,
      });
    }
  }
}
interface iDeleUser {
  userId: number;
}
interface IUserFromDataClass {
  realName: string;
  loginName: string;
  orgId?: number | null;
  treeId?: number;
  orgName: string;
  password?: string;
  roleId: number;
  id?: number;
}
export default UserTable;
